package com.education.business.service.education;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.education.business.service.system.*;
import com.education.common.utils.FileUtil;
import com.education.common.utils.ZipUtils;
import com.education.model.dto.TestPaperInfoStudentDto;
import com.education.model.entity.*;
import com.education.model.subproject.ExamTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UpDownLoadservice {
    @Autowired
    private ExamTaskService examTaskService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private TestPaperInfoService testPaperInfoService;
    @Autowired
    private QuestionInfoService questionInfoService;
    @Autowired
    private GradeInfoService gradeInfoService;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private SubjectInfoService subjectInfoService;
    @Autowired
    private SystemAdminRoleService systemAdminRoleService;
    @Autowired
    private SystemDictService systemDictService;
    @Autowired
    private SystemDictValueService systemDictValueService;
    @Autowired
    private SystemMenuService systemMenuService;
    @Autowired
    private SystemRoleMenuService systemRoleMenuService;
    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private TestPaperQuestionInfoService testPaperQuestionInfoService;
    @Autowired
    private TestPaperInfoStudentService testPaperInfoStudentService;
    @Autowired
    private StudentQuestionAnswerService studentQuestionAnswerService;
    @Autowired
    private ExamInfoService examInfoService;


    /**
     * 考试任务导出
     * 根据考试任务ID读写数据库数据成json数据
     * 将读写后的json数据压缩成压缩包
     * 删除读写json数据后的目录
     * @param examTaskId
     * @return 压缩包的位置（String）
     */
    public String downLoadTaskById(HttpServletResponse response,int examTaskId){
        //创建文件夹
        FileUtil.CreateFile("ExamTask");
        FileUtil.CreateFile("ExamTaskZip");
        ExamTask examTasks = examTaskService.ExamTaskById(examTaskId);
        systemAdminService.selectByTaskId(examTasks.getAdminId());
        systemAdminRoleService.selectByAdminId(examTasks.getAdminId());
        SystemRole systemRole = systemRoleService.findRoleByAdminId(examTasks.getAdminId());
        systemDictService.SystemDict();
        systemDictValueService.SystemDictValue();
        systemRoleMenuService.SystemRoleMenuByRoleId(systemRole.getId());
        List systemRoles = new ArrayList();
        systemRoles.add(systemRole.getId());
        systemMenuService.selectMenuListByRoles(systemRoles);
        List<TestPaperInfo> testPaperInfo = testPaperInfoService.testPaperInfoListByTaskId(examTasks.getId());
        JSONArray testPaperArray = JSON.parseArray(JSON.toJSONString(testPaperInfo));
        List<TestPaperQuestionInfo> testPaperQuestionInfoList = new ArrayList();
        testPaperQuestionInfoList = testPaperQuestionInfoService.TestPaperQuestionInfoByPaperId(testPaperInfo);
        questionInfoService.questionById(testPaperQuestionInfoList);
        testPaperInfoStudentService.TestPaperInfoStudentByTaskId(examTasks.getId());
        studentInfoService.selectStudentByTestPaperId(testPaperArray);
        gradeInfoService.gradeInfoById(testPaperArray);
        subjectInfoService.selectByTestPaperId(testPaperArray);
        //压缩包名字
        String zipName = "考试任务"+"_"+examTasks.getName()+".zip";
        //需要压缩的目录
        Path folder = Paths.get("education-api"+ File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"ExamTask");
        //压缩后的位置
        //相对路径
        String absolutePath = System.getProperty("user.dir");//项目路径
        String FileZip = "education-api"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"ExamTaskZip"+File.separator;
        Path zipFile = Paths.get(FileZip+zipName);
        //压缩目录
        try {
            ZipUtils.packet(folder,zipFile);
        }catch (IOException e){
            e.printStackTrace();
        }
        //删除目录
        File delfile = folder.toFile();
        FileUtil.deleteDir(delfile);

        File file = new File(zipFile.toString());
        if (!file.exists()) return "文件不存在";
        try(
                InputStream inStream = new FileInputStream(zipFile.toString());
                OutputStream os = response.getOutputStream();
        ) {
            response.reset();
            response.setContentType("application/force-download");// 设置强制下载不打开
            //下载后的文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName,"UTF-8"));
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len = inStream.read(buff)) > 0) {
                os.write(buff, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return "下载文件异常";
        }
        return zipFile.toString();
    }
    /**
     * 考试任务导入
     * 根据传入的压缩包路径进行解压
     * 导入解压后的json文件到数据库
     * 删除解压后的目录
     * @param path
     * @return
     */
    public String upLoadTask(String path,String name){
        File f = new File(path+File.separator+"ExamTask");
        if (f.exists()){
            FileUtil.deleteDir(f);
        }

        //压缩后的目录
        Path targetDir = Paths.get(path+File.separator+"ExamTask"+File.separator);
        //压缩文件的位置
        Path fileZip = Paths.get(path+File.separator+name);
        try {
            ZipUtils.unPacket(fileZip,targetDir);
        }catch (IOException e){
            e.printStackTrace();
        }
        String file = targetDir.toString()+"\\";
        //考试任务
        String examTask = FileUtil.ReadFile(file,"examTasks.json");
        examTaskService.saveAll(JSONObject.parseObject(examTask,ExamTask.class));
        //监考员
        String systemAdmin = FileUtil.ReadFile(file,"systemAdmin.json");
        systemAdminService.saveAll(JSONObject.parseObject(systemAdmin,SystemAdmin.class));
        //监考员权限
        String systemAdminRole = FileUtil.ReadFile(file,"systemAdminRole.json");
        systemAdminRoleService.saveAll(JSONObject.parseObject(systemAdminRole,SystemAdminRole.class));
        //角色
        String systemRole = FileUtil.ReadFile(file,"systemRole.json");
        systemRoleService.saveAll(JSONObject.parseObject(systemRole,SystemRole.class));
        //字典
        String systemDict = FileUtil.ReadFile(file,"systemDict.json");
        JSONArray jsonArray = JSONArray.parseArray(systemDict);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            systemDictService.saveAll(JSONObject.parseObject(str, SystemDict.class));
        }
        //字典值
        String systemDictValue = FileUtil.ReadFile(file,"systemDictValue.json");
        jsonArray = JSONArray.parseArray(systemDictValue);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            systemDictValueService.saveAll(JSONObject.parseObject(str, SystemDictValue.class));
        }
        //角色菜单
        String systemRoleMenus = FileUtil.ReadFile(file,"systemRoleMenus.json");
        jsonArray = JSONArray.parseArray(systemRoleMenus);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            systemRoleMenuService.saveAll(JSONObject.parseObject(str, SystemRoleMenu.class));
        }
        //菜单
        String systemMenu = FileUtil.ReadFile(file,"systemMenu.json");
        jsonArray = JSONArray.parseArray(systemMenu);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            systemMenuService.saveAll(JSONObject.parseObject(str, SystemMenu.class));
        }
        //试卷
        String testPaperInfo = FileUtil.ReadFile(file,"testPaperInfo.json");
        jsonArray = JSONArray.parseArray(testPaperInfo);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            testPaperInfoService.saveAll(JSONObject.parseObject(str, TestPaperInfo.class));
        }
        //试卷与题目中间表
        String testPaperQuestionInfo = FileUtil.ReadFile(file,"testPaperQuestionInfo.json");
        jsonArray = JSONArray.parseArray(testPaperQuestionInfo);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            testPaperQuestionInfoService.saveAll(JSONObject.parseObject(str, TestPaperQuestionInfo.class));
        }
        //试卷题目
        String questionInfo = FileUtil.ReadFile(file,"questionInfo.json");
        jsonArray = JSONArray.parseArray(questionInfo);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            questionInfoService.saveAll(JSONObject.parseObject(str, QuestionInfo.class));
        }
        //试卷与考生中间表
        String testPaperInfoStudent = FileUtil.ReadFile(file,"testPaperInfoStudent.json");
        jsonArray = JSONArray.parseArray(testPaperInfoStudent);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            testPaperInfoStudentService.saveAll(JSONObject.parseObject(str, TestPaperInfoStudent.class));
        }
        //考生
        String studentInfo = FileUtil.ReadFile(file,"studentInfo.json");
        jsonArray = JSONArray.parseArray(studentInfo);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            studentInfoService.saveAll(JSONObject.parseObject(str,StudentInfo.class));
        }
        //年级
        String gradeInfo = FileUtil.ReadFile(file,"gradeInfo.json");
        jsonArray = JSONArray.parseArray(gradeInfo);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            gradeInfoService.saveAll(JSONObject.parseObject(str, GradeInfo.class));
        }
        //学科
        String subjectInfo = FileUtil.ReadFile(file,"subjectInfo.json");
        jsonArray = JSONArray.parseArray(subjectInfo);
        for(int i=0;i<jsonArray.size();i++){
            String str = jsonArray.getString(i);
            subjectInfoService.saveAll(JSONObject.parseObject(str, SubjectInfo.class));
        }

        return targetDir.toString();
    }


    /**
     * 考生答卷导出
     *
     * @return
     */
    public String downLoadStudentQuestionAnswer(HttpServletResponse response, List<TestPaperInfoStudentDto> studentInfos) {
        //创建文件夹
        FileUtil.CreateFile("StudentQuestionAnswer");
        FileUtil.CreateFile("StudentQuestionAnswerZip");

        List<ExamInfo> examInfos = new ArrayList<>();
        List studentQuestionAnswers = new ArrayList<>();
        for (TestPaperInfoStudentDto testPaperInfoStudentDto:studentInfos) {
            studentQuestionAnswers.add(studentQuestionAnswerService.selectQuesionAnswerAll(testPaperInfoStudentDto.getStudentId()));
            ExamInfo examInfo = examInfoService.selectExamInfoByStuId(testPaperInfoStudentDto.getStudentId());
            examInfos.add(examInfo);
        }

        FileUtil.WriteFile("../StudentQuestionAnswer/studentQuestionAnswers" + ".json", FileUtil.tojson(studentQuestionAnswers));
        FileUtil.WriteFile("../StudentQuestionAnswer/examInfos" + ".json", FileUtil.tojson(examInfos));
        //压缩包名字
        String zipName = "考生答卷"+".zip";
        //需要压缩的目录
        Path folder = Paths.get("education-api"+ File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"StudentQuestionAnswer");
        //压缩后的位置
        //相对路径
        String FileZip = "education-api"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"StudentQuestionAnswerZip"+File.separator;
        Path zipFile = Paths.get(FileZip+zipName);
        //压缩目录
        try {
            ZipUtils.packet(folder,zipFile);
        }catch (IOException e){
            e.printStackTrace();
        }
        //删除目录
        File delfile = folder.toFile();
        FileUtil.deleteDir(delfile);

        return zipFile.toString();
    }

    /**
     * 考生答卷导入
     *
     * @return
     */
    public String upLoadStudentQuestionAnswer(String path, String name) {
        File f = new File(path + File.separator + "StudentQuestionAnswer");
        if (f.exists()) {
            FileUtil.deleteDir(f);
        }
        //压缩后的目录
        Path targetDir = Paths.get(path + File.separator + "StudentQuestionAnswer" + File.separator);
        //压缩文件的位置
        Path fileZip = Paths.get(path + File.separator + name);
        try {
            ZipUtils.unPacket(fileZip, targetDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String file = targetDir.toString() + "\\";

        //考生考试信息
        String examInfoList = FileUtil.ReadFile(file, "examInfos.json");
        JSONArray jsonArray = JSONArray.parseArray(examInfoList);
        List<ExamInfo> examInfos = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String str = jsonArray.getString(i);
            ExamInfo examInfo = JSONObject.parseObject(str, ExamInfo.class);
            examInfoService.save(JSONObject.parseObject(str, ExamInfo.class));
            examInfos.add(examInfoService.selectExamByStuIdPaperId(examInfo.getStudentId(),examInfo.getTestPaperInfoId()));
        }
        //考生答题卡
        String studentQuestionAnswer = FileUtil.ReadFile(file, "studentQuestionAnswers.json");
        List list = JSON.parseObject(studentQuestionAnswer, List.class);
        for (int i = 0; i < list.size(); i++) {
            List<StudentQuestionAnswer> studentQuestionAnswers = (List) list.get(i);
            for (int j = 0; j < studentQuestionAnswers.size(); j++) {
                StudentQuestionAnswer studentAnswer = JSONObject.parseObject(String.valueOf(studentQuestionAnswers.get(j)), StudentQuestionAnswer.class);
                if (studentAnswer.getStudentId()==examInfos.get(i).getStudentId()||studentAnswer.getStudentId().equals(examInfos.get(i).getStudentId())){
                    studentAnswer.setExamInfoId(examInfos.get(i).getId());
                }
                studentQuestionAnswerService.save(studentAnswer);
            }
        }
        return "";
    }




}
